package com.douxg.fastCoding.spring.util;

import com.douxg.fastCoding.spring.consts.BizCode;
import com.douxg.fastCoding.spring.exception.BizRuntimeException;
import lombok.Data;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @Description
 * @Auther douxg
 * @Date 2020/7/31 10:34
 */
@Slf4j
public class DownUtil {
    public static void downZip(String downFileName, List<DownFile> downFiles, HttpServletResponse response) {
        try {
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(downFileName, "UTF-8"));
            response.setContentType("application/zip;charset=utf-8");
            response.setCharacterEncoding("UTF-8");
            ZipOutputStream zipOutputStream = new ZipOutputStream(response.getOutputStream());

            for (DownFile downFile : downFiles) {
                checkDownFile(downFile);
                ZipEntry zipEntryXtv = new ZipEntry(downFile.getName());
                zipOutputStream.putNextEntry(zipEntryXtv);
                zipOutputStream.write(downFile.getContent().getBytes());
            }
            zipOutputStream.close();
        } catch (Exception e) {
            throw new BizRuntimeException(BizCode.DOWN_ERROR, e);
        }
    }

    public static void down(String downFileName, String content, HttpServletResponse response) {
        try {
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(downFileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new BizRuntimeException(BizCode.DOWN_ERROR, e);
        }
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("UTF-8");
        try (PrintWriter writer = response.getWriter()) {
            writer.print(content);
        } catch (Exception e) {
            throw new BizRuntimeException(BizCode.DOWN_ERROR, e);
        }
    }

    public static void checkDownFile(DownFile downFile) {
        CheckUtil.isBlank(downFile.getName());
        CheckUtil.isBlank(downFile.getContent());
    }

    @Data
    @Accessors(chain = true)
    public static class DownFile {
        private String name;
        private String content;
    }
}
